package com.vone.ui;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;

import layout.TableLayout;

/**
 * 遮住层
 * @author admin
 */
public class MyCoverJPanel extends JPanel {
	private static final long serialVersionUID = 1L;
	private MyCoverJPanel myCoverJPanel = this; // 遮罩层
	private JLabel shadowImage = null;// 状态图片
	private int jframeWidth=0;
	private int jframeHeight=0;
	
	// 打开关闭遮罩层
	private ExecutorService executor = Executors.newSingleThreadExecutor();

	/**
	 * @param task Runnable任务
	 * @param jframeWidth 设置窗体宽度
	 * @param jframeHeight 设置窗体高度
	 * @param j 加到哪个窗体上面
	 */
	public MyCoverJPanel(Runnable task, final int jframeWidth, final int jframeHeight, final JLayeredPane j) {
		this.jframeWidth=jframeWidth;
		this.jframeHeight=jframeHeight;
		// 遮住层
		ImageIcon icon = new ImageIcon(getClass().getResource("/image/loading.gif"));
		shadowImage = new JLabel(icon);
		shadowImage.setOpaque(false);//设置透明
//		shadowImage.setBackground(new Color(255, 255, 255));
		myCoverJPanel.setOpaque(false);
		myCoverJPanel.setVisible(false);
		myCoverJPanel.setBackground(new Color(205, 205, 205, 50));
		myCoverJPanel.addMouseListener(new MouseAdapter() {
		});
		myCoverJPanel.setLayout(
				new TableLayout(new double[][] { { 0, 0.46, 0.08, 0.46, 0 }, { 0, 0.4475, 0.105, 0.4475, 0 } }));
		myCoverJPanel.add(shadowImage, "2,2");

		// shadow.setVisible(true);
		executor.execute(new Runnable() {
			@Override
			public void run() {
				myCoverJPanel.setBounds(0, 0, jframeWidth, jframeHeight);
				j.add(myCoverJPanel, new Integer(Integer.MAX_VALUE));// 放到JFrame最顶层
				myCoverJPanel.setVisible(true);
			}
		});
		executor.execute(task);
		executor.execute(new Runnable() {
			@Override
			public void run() {
				j.remove(myCoverJPanel);
				j.repaint();
				myCoverJPanel.setVisible(false);
				/*可以关闭 ExecutorService，这将导致其拒绝新任务。提供两个方法来
				关闭 ExecutorService。shutdown() 方法在终止前允许执行以
				前提交的任务，而 shutdownNow() 方法阻止等待任务启动并试图停止
				当前正在执行的任务。在终止时，执行程序没有任务在执行，也没有任务在
				等待执行，并且无法提交新任务。应该关闭未使用的 ExecutorService
				以允许回收其资源。*/
				executor.shutdown();
				executor.shutdownNow();
			}
		});
	}
	//设置面板半透明
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		Graphics2D graphics2d = (Graphics2D) g.create();
		graphics2d.setComposite(AlphaComposite.SrcOver.derive(.15f));//设置透明度
		graphics2d.setColor(Color.white);
		graphics2d.fillRect(0, 0, jframeWidth, jframeHeight);
		graphics2d.dispose();
	}
}